package com.example.emos.wx.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;
//http://127.0.0.1:8080/emos-wx-api/swagger-ui.html
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 创建并返回一个Docket实例，用于配置Swagger文档生成规则
     */
    @Bean
    public Docket createRestApi() {
        // 创建Docket实例
        Docket docket = new Docket(DocumentationType.SWAGGER_2);

        // 构建API信息
        ApiInfoBuilder builder = new ApiInfoBuilder();
        builder.title("EMOS在线办公系统"); // 设置API文档的标题
        ApiInfo info = builder.build(); // 构建ApiInfo实例
        docket.apiInfo(info); // 将ApiInfo设置到Docket实例中

        // 选择API的路径和方法
        ApiSelectorBuilder selectorBuilder = docket.select(); // 获取ApiSelectorBuilder实例
        selectorBuilder.paths(PathSelectors.any()); // 选择所有API路径
        selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)); // 选择带有ApiOperation注解的方法
        docket = selectorBuilder.build(); // 构建选择器并设置到Docket实例中

        // 设置API访问的token
        ApiKey apiKey = new ApiKey("token", "token", "header"); // 创建ApiKey实例
        List<ApiKey> apiKeyList = new ArrayList<>(); // 创建ApiKey列表
        apiKeyList.add(apiKey); // 将ApiKey添加到列表中
        docket.securitySchemes(apiKeyList); // 将ApiKey列表设置到Docket实例中

        // 设置API访问的权限范围
        AuthorizationScope scope = new AuthorizationScope("global", "accessEverything"); // 创建AuthorizationScope实例
        AuthorizationScope[] scopes = {scope}; // 创建AuthorizationScope数组
        SecurityReference reference = new SecurityReference("token", scopes); // 创建SecurityReference实例
        List refList = new ArrayList(); // 创建SecurityReference列表
        refList.add(reference); // 将SecurityReference添加到列表中
        SecurityContext context = SecurityContext.builder().securityReferences(refList).build(); // 创建SecurityContext实例
        List cxtList = new ArrayList(); // 创建SecurityContext列表
        cxtList.add(context); // 将SecurityContext添加到列表中
        docket.securityContexts(cxtList); // 将SecurityContext列表设置到Docket实例中

        // 返回配置好的Docket实例
        return docket;
    }
}
